import http.server
import socketserver
import os
import base64

# Basic authentication credentials
USERNAME = 'admin'
PASSWORD = 'passw0rd_alert@cmp'

# Directory to save Docker image tar files
UPLOAD_DIR = '/path/to/upload/directory/'

class RequestHandler(http.server.SimpleHTTPRequestHandler):

    def do_POST(self):
        auth_header = self.headers.get('Authorization')
        if not auth_header:
            self.send_response(401)
            self.send_header('WWW-Authenticate', 'Basic realm="Auth Realm"')
            self.end_headers()
            return

        auth_token = auth_header.split(maxsplit=1)[-1]
        username, password = base64.b64decode(auth_token).decode().split(':', 1)

        if username != USERNAME or password != PASSWORD:
            self.send_response(401)
            self.send_header('WWW-Authenticate', 'Basic realm="Auth Realm"')
            self.end_headers()
            return

        content_length = int(self.headers.get('Content-Length', 0))
        if content_length == 0:
            self.send_response(400)
            self.end_headers()
            return

        # Read the POST body data (Docker image tar file)
        image_data = self.rfile.read(content_length)

        # Save the Docker image tar file to the upload directory
        with open(os.path.join(UPLOAD_DIR, 'image.tar'), 'wb') as f:
            f.write(image_data)

        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'File uploaded successfully')

if __name__ == "__main__":
    PORT = 8080
    handler = RequestHandler
    with socketserver.TCPServer(("", PORT), handler) as httpd:
        print("Server started at port", PORT)
        httpd.serve_forever()


# POST example:
# curl -X POST -u admin:passw0rd_alert@cmp -H "Content-Disposition: attachment; filename=<镜像tar包名>" --data-binary @<镜像tar包文件存放路径>/<镜像tar包名> http://22.249.128.11:8089